<?php
namespace app\command;

use app\common\service\MembershipDaemonService;
use support\Log;

/**
 * 会员到期处理守护进程
 * 使用方法: php webman membership:daemon
 */
class MembershipDaemon
{
    /**
     * 命令名称
     */
    protected static $defaultName = 'membership:daemon';
    
    /**
     * 命令描述
     */
    protected static $defaultDescription = '处理会员到期和自动续费的守护进程';
    
    /**
     * 执行命令
     */
    public function execute()
    {
        echo "Starting membership daemon...\n";
        Log::info('Membership daemon started');
        
        try {
            // 处理即将到期的会员
            MembershipDaemonService::processExpiringMemberships();
            
            // 处理自动续费
            MembershipDaemonService::processAutoRenewals();
            
            echo "Membership daemon completed successfully.\n";
            Log::info('Membership daemon completed successfully');
            
        } catch (\Exception $e) {
            echo "Membership daemon failed: " . $e->getMessage() . "\n";
            Log::error('Membership daemon failed: ' . $e->getMessage());
            return 1;
        }
        
        return 0;
    }
    
    /**
     * 以守护进程模式运行（持续运行）
     */
    public function daemon()
    {
        echo "Starting membership daemon in continuous mode...\n";
        Log::info('Membership daemon started in continuous mode');
        
        while (true) {
            try {
                // 每小时运行一次
                MembershipDaemonService::processExpiringMemberships();
                MembershipDaemonService::processAutoRenewals();
                
                echo "Membership daemon cycle completed at " . date('Y-m-d H:i:s') . "\n";
                Log::info('Membership daemon cycle completed');
                
                // 等待1小时
                sleep(3600);
                
            } catch (\Exception $e) {
                echo "Membership daemon error: " . $e->getMessage() . "\n";
                Log::error('Membership daemon error: ' . $e->getMessage());
                
                // 出错后等待10分钟再重试
                sleep(600);
            }
        }
    }
}